package domain;

//SaleController.java
import javax.servlet.annotation.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import java.io.IOException;

@WebServlet("/SaleController")
public class SaleController extends HttpServlet {
 private Register register;

 public SaleController() {
     Store store = new Store();
     this.register = store.getRegister();
 }

 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String action = request.getParameter("action");
     if ("startSale".equals(action)) {
         startSale();
         response.sendRedirect("sale.jsp");
     } else if ("addItem".equals(action)) {
         processItem(request, response);
     } else if ("completeSale".equals(action)) {
         completeSale(request, response);
     }
 }

 public void startSale() {
     register.makeNewSale();
 }

 public void processItem(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     String itemIdStr = request.getParameter("itemId");
     int quantity = Integer.parseInt(request.getParameter("quantity"));
     ItemID id = new ItemID(Integer.parseInt(itemIdStr));
     register.enterItem(id, quantity);
     
     // 重定向回销售页面，显示更新后的信息
     request.setAttribute("totalAmount", register.getCurrentSale().getTotal().getAmount());
     request.setAttribute("lineItems", register.getCurrentSale().getLineItems());
     request.getRequestDispatcher("sale.jsp").forward(request, response);
 }

 public void completeSale(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     double cashTendered = Double.parseDouble(request.getParameter("cashTendered"));
     register.makePayment(new Money(cashTendered));
     Money balance = register.getCurrentSale().getBalance();
     
     request.setAttribute("balance", balance.getAmount());
     request.getRequestDispatcher("sale.jsp").forward(request, response);
 }
}
